<template>
  <div class="management-container">
    <div class="page-header">
      <div class="header-title">
        <h1>角色管理</h1>
        <p>管理系统角色信息、权限分配和状态控制</p>
      </div>
      <div class="header-actions">
        <a-button type="primary" @click="showAddModal">
          <PlusOutlined />添加角色</a-button
        >
      </div>
    </div>

    <!-- 角色列表 -->
    <a-card class="table-card">
      <a-table
        style="width: 100%; overflow-y: auto"
        :columns="columns"
        :data-source="roles"
        :loading="tableLoading"
        row-key="id"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ record, column }">
          <!-- 状态列 -->
            <a-switch v-if="column.dataIndex === 'active'"
                v-model:checked="record.active"
                checked-children="启用"
                un-checked-children="禁用"
                @change="handleActiveChange(record, $event)"
            />
          <div class="" v-if="column.key === 'createdAt'">
            {{ formatDateTime(record.createdAt) }}
          </div>
          <div class="table-actions" v-if="column.key === 'action'">
            <a-flex :gap="5">
              
              <a-button
                type="primary"
                ghost
                danger
                shape="circle"
                @click="confirmDelete(record.id)"
                :hidden="record.isAdmin"
              >
                <template #icon>
                  <ClearOutlined />
                </template>
              </a-button>
              <a-button
                ghost
                type="primary"
                shape="circle"
                @click="showPermissionModal(record)"
              >
                <template #icon>
                  <SettingOutlined />
                </template>
              </a-button>
              <a-button
                type="primary"
                shape="circle"
                @click="showEditModal(record)"
              >
                <template #icon>
                  <EditOutlined />
                </template>
              </a-button>
              <a-button
                type="primary"
                shape="circle"
                style="background-color:#1890ff"
                :hidden="record.isAdmin"
                @click="showTreeModal(record)"

              >
                <template #icon>
                 <MenuOutlined  />
                </template>
                
              </a-button>
            </a-flex>
          </div>
        </template>
      </a-table>
    </a-card>

    <!-- 添加角色模态框 -->
    <a-modal
      v-model:open="addModalVisible"
      title="添加角色"
      @ok="handleAdd"
      @cancel="closeAddModal"
      okText="新建"
      cancelText="取消"
    >
      <a-form :model="newRole" layout="vertical">
        <a-form-item label="角色名称">
          <a-input v-model:value="newRole.name" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item label="角色描述">
          <a-textarea
            v-model:value="newRole.description"
            placeholder="请输入角色描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑角色模态框 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑角色"
      @ok="handleEdit"
      @cancel="closeEditModal"
      okText="保存"
      cancelText="取消"
    >
      <a-form :model="editingRole" layout="vertical">
        <a-form-item label="角色名称">
          <a-input
            v-model:value="editingRole.name"
            placeholder="请输入角色名称"
          />
        </a-form-item>
        <a-form-item label="角色描述">
          <a-textarea
            v-model:value="editingRole.description"
            placeholder="请输入角色描述"
          />
        </a-form-item>
        <a-form-item label="角色状态">
          <a-switch
            v-model:checked="editingRole.active"
            @change="handleStatusChange"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认模态框 -->
    <a-modal
      v-model:open="deleteModalVisible"
      title="确认删除"
      @ok="handleDelete"
      @cancel="closeDeleteModal"
      okType="danger"
      cancelText="取消"
      okText="删除"
    >
      <p>确定要删除该角色吗？</p>
    </a-modal>
    <!-- 权限分配模态框 -->
    <permission-modal
      :currentRole="currentRole"
      :permissionCategories="state.permissionCategories"
      ref="permissionModalRef"
    ></permission-modal>

    <!-- 树状图模态框 -->
    <tree-modal 
    ref="treeModalRef"
    ></tree-modal>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import { formatDateTime } from "@/utils";
import { PlusOutlined } from "@ant-design/icons-vue";
import {
  getRoles,
  addRole,
  updateRole,
  deleteRole,
  getPermissions,
  getAllPermissions,
  getRoleMenusById
} from "@/api/role";
import PermissionModal from "@/components/PermissionModal.vue";
import TreeModal from "@/components/TreeModal.vue";
import menuApi from '@/api/menu'
import {
  EditOutlined,
  ClearOutlined,
  SettingOutlined,
  MenuOutlined 
} from "@ant-design/icons-vue";
// 表格数据和配置
const roles = ref([]);
const tableLoading = ref(false);
const columns = [
  {
    title: "角色名称",
    dataIndex: "name",
    key: "name",
    fixed: true,
    width: 150,
  },
  {
    title: "角色描述",
    dataIndex: "description",
    key: "description",
  },
  { title: "创建时间", dataIndex: "createdAt", key: "createdAt" },
  { title: "角色状态", dataIndex: "active", key: "active",width: 120 },
  { title: "操作", key: "action", fixed: "right" },
];
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});
const state = reactive({
  permissionCategories: [],
});
// 模态框状态
const addModalVisible = ref(false);
const editModalVisible = ref(false);
const deleteModalVisible = ref(false);
const treeModalRef = ref(null);
const menuList = ref([])
const permissionModalRef = ref(null);
// 表单数据
const newRole = reactive({ name: "", description: "" });

const editingRole = reactive({
  id: "",
  name: "",
  description: "",
  active: false,
});
const deletingRoleId = ref("");
const currentRole = ref({});

// 生命周期
onMounted(() => {
  fetchRoles();
  fetchPermissions();
  fetchMenus();

});
const fetchMenus = async () => {
  try {
    const response = await menuApi.getMenus();
    const newMenu = buildMenuTree(response)
    menuList.value = newMenu;
  } catch (error) {
    message.error("获取菜单列表失败");
    console.error("Failed to fetch menus:", error);
  }
}
const buildMenuTree = (menuList) => {
  return menuList.map(item => ({
    ...item,
    disabled: !item.status,
    key: item._id,
    children: item.children ? buildMenuTree(item.children) : []
  }))
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await getRoles({
      page: pagination.current,
      pageSize: pagination.pageSize,
      searchKey: "",
    });
    roles.value = response.lists;
    pagination.total = response.total;
  } catch (error) {
    message.error("获取角色列表失败");
    console.error("Failed to fetch roles:", error);
  }
};

// 获取权限树
const fetchPermissions = async () => {
  try {
    const response = await getAllPermissions();
    // 检查响应是否为空
    if (!response || Object.keys(response).length === 0) {
      console.error("Empty permissions response");
      return;
    }

    const list = Object.keys(response).map((key) => {
      return {
        name: key,
        key: key,
        children: Object.keys(response[key]).map((item) => ({
          name: item,
          key: response[key][item],
        })),
      };
    });

    state.permissionCategories = list;
  } catch (error) {
    console.error("Failed to fetch permissions:", error);
    message.error("获取权限失败: " + error.message);
  }
};

// 表格分页变化
const handleTableChange = (pagination) => {
  Object.assign(pagination, pagination);
  fetchRoles();
};

// 添加角色
const showAddModal = () => {
  newRole.name = "";
  newRole.description = "";
  addModalVisible.value = true;
};

const closeAddModal = () => {
  addModalVisible.value = false;
};

const handleAdd = async () => {
  if (!newRole.name) {
    message.warning("请输入角色名称");
    return;
  }
  try {
    await addRole(newRole);
    message.success("添加角色成功");
    closeAddModal();
    fetchRoles();
  } catch (error) {
    message.error("添加角色失败");
    console.error("Failed to add role:", error);
  }
};

// 编辑角色
const showEditModal = (role) => {
  console.log(role);
  editingRole.id = role.id;
  editingRole.name = role.name;
  editingRole.description = role.description;
  editingRole.active = role.active;

  editModalVisible.value = true;
};
const showTreeModal = (record) => {
  if(treeModalRef.value && menuList.value.length > 0) {
    treeModalRef.value.visible = true;
    treeModalRef.value.currentRole = record;
    treeModalRef.value.menuList = menuList.value
    

    getRoleMenus(record.id).then(res => {
      treeModalRef.value.checkedKeys = res
      treeModalRef.value.checkAllMenus = false
    })

  }
}
const getRoleMenus = async (roleId) => {
  try {
    const response = await getRoleMenusById(roleId);
    return new Promise((resolve, reject) => {
      if (response) {
        resolve(response);
      } else {
        reject(new Error("No menus found"));
      }
    });
  } catch (error) {
    message.error("获取角色菜单失败");
    console.error("Failed to fetch role menus:", error);
  }
} 
const closeEditModal = () => {
  editModalVisible.value = false;
};
const handleStatusChange = (checked) => {
  editingRole.active = checked;
};
const handleActiveChange = async (record, checked) => {
  const newStatus = checked;
  tableLoading.value = true;
  try {
    await updateRole(record.id, record);
    message.success(`角色已${newStatus ? '启用' : '禁用'}`);
    tableLoading.value = false;
  } catch (error) {
    tableLoading.value = false;
  }
};

const handleEdit = async () => {
  if (!editingRole.name) {
    message.warning("请输入角色名称");
    return;
  }
  try {
    await updateRole(editingRole.id, editingRole);
    message.success("编辑角色成功");
    closeEditModal();
    fetchRoles();
  } catch (error) {
    message.error("编辑角色失败");
    console.error("Failed to update role:", error);
  }
};

// 删除角色
const confirmDelete = (id) => {
  deletingRoleId.value = id;
  deleteModalVisible.value = true;
};

const closeDeleteModal = () => {
  deleteModalVisible.value = false;
};

const handleDelete = async () => {
  try {
    await deleteRole(deletingRoleId.value);
    message.success("删除角色成功");
    closeDeleteModal();
    fetchRoles();
  } catch (error) {
    message.error("删除角色失败");
    console.error("Failed to delete role:", error);
  }
};

// 分配权限
const showPermissionModal = async (role) => {
  currentRole.value = role;
  // 加载角色当前权限
  const res = await fetchRolePermissions(role.id);
  if (permissionModalRef.value && state.permissionCategories.length > 0) {
    permissionModalRef.value.activeCategory = state.permissionCategories[0].key;
    permissionModalRef.value.checkedPermissionKeys = res;
    permissionModalRef.value.visible = true;
    permissionModalRef.value.isCheckedAll(state.permissionCategories[0].children);
  }
};

const fetchRolePermissions = async (roleId) => {
  try {
    const response = await getPermissions(roleId);
    return new Promise((resolve, reject) => {
      if (response) {
        resolve(response);
      } else {
        reject(new Error("No permissions found"));
      }
    });
  } catch (error) {
    message.error("获取角色权限失败");
    console.error("Failed to fetch role permissions:", error);
  }
};
</script>

<style scoped lang="scss">
.management-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 64px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .header-title {
    h1 {
      margin: 0 0 8px 0;
      font-size: 20px;
      font-weight: 600;
      color: #1f2329;
    }
    p {
      margin: 0;
      color: #6b7280;
      font-size: 14px;
    }
  }

  .header-actions {
    display: flex;
  }
}

.table-card {
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}
</style>
